<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noodp"/><title>TensorFlow2.1入门学习笔记(6)——激活函数 | Yasin&#39;s Blog</title><meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content=""/>
<meta name="twitter:title" content="TensorFlow2.1入门学习笔记(6)——激活函数"/>
<meta name="twitter:description" content=""/><meta name="twitter:creator" content="@wangyuexin8"/><meta name="Description" content="KEEP KWARKING"><meta property="og:title" content="TensorFlow2.1入门学习笔记(6)——激活函数" />
<meta property="og:description" content="常见函数tf.where(条件语句，真返回A，假返回B)1 2 3 4 5 6 import tensorflow as tf a = tf.constant([1, 2, 3, 1, 1]) b = tf.constant([0, 1, 3, 4, 5]) # 若a&gt;b，返回a对应位置的元" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://blog.aimoon.top/activation/" /><meta property="og:image" content="https://blog.aimoon.top/images/favicon.svg"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2020-05-20T09:34:53&#43;08:00" />
<meta property="article:modified_time" content="2021-03-29T11:34:14&#43;08:00" /><meta property="og:site_name" content="Yasin&#39;s Blog" />

<meta name="application-name" content="YASIN">
<meta name="apple-mobile-web-app-title" content="YASIN"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/favicon.svg" type="image/x-icon"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://blog.aimoon.top/activation/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "TensorFlow2.1入门学习笔记(6)——激活函数",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/blog.aimoon.top\/activation\/"
        },"image": ["https:\/\/blog.aimoon.top\/images\/cover.png"],"genre": "posts","keywords": "activation, function","wordCount":  1667 ,
        "url": "https:\/\/blog.aimoon.top\/activation\/","datePublished": "2020-05-20T09:34:53+08:00","dateModified": "2021-03-29T11:34:14+08:00",
        "publisher": {
            "@type": "Person",
            "name": "Wang Yuexin", "image": [
            {
            "@type": "ImageObject",
            "url": "https:\/\/blog.aimoon.top\/images\/avatars.png"
            }
            ]},"author": {
                "@type": "Person",
                "name": "Wang Yuexin"
            },"description": ""
    }
    </script><script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [{
            "@type": "ListItem",
            "position": 1,
            "name": "主页",
            "item": "https:\/\/blog.aimoon.top"
        },{
            "@type": "ListItem",
            "position": 2,
            "name": "TF2.1学习笔记",
            "item": "https://blog.aimoon.top/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"
        },{
                "@type": "ListItem",
                "position": 3,
                "name": "TensorFlow2.1入门学习笔记(6)——激活函数"
            }]
    }
</script></head>
    <body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('light' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'light' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header>
    <div class="desktop header" id="header-desktop">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="Yasin&#39;s Blog" class="header-logo logo-svg">Yasin&#39;s Blog</a>
            </div>
            <div class="menu">
                <nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul class="menu-inner"><li>
                            <a class="menu-item" href="/posts/"> 目录 </a>
                        </li><li>
                            <a class="menu-item" href="/tags/"> 标签 </a>
                        </li><li>
                            <a class="menu-item" href="/categories/"> 归档 </a>
                        </li><li>
                            <a class="menu-item" href="/comments/"> 留言 </a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" rel="noopener noreffer" target="_blank"> 主页 </a>
                        </li></ul>
                </nav><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="search……" id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <span class="svg-icon icon-search"></span>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <span class="svg-icon icon-cancel"></span>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <span class="svg-icon icon-loading"></span>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <span class="svg-icon icon-moon"></span>
                </a>
            </div>
        </div>
    </div><div class="mobile header" id="header-mobile">
        <div class="header-container">
            <div class="header-wrapper">
                <div class="header-title">
                    <a href="/" title="Yasin&#39;s Blog" class="header-logo">Yasin&#39;s Blog</a>
                </div>
                <div class="menu-toggle" id="menu-toggle-mobile">
                    <span></span><span></span><span></span>
                </div>
            </div>
            <div class="menu" id="menu-mobile"><div class="search-wrapper">
                        <div class="search mobile" id="search-mobile">
                            <input type="text" placeholder="search……" id="search-input-mobile">
                            <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                                <span class="svg-icon icon-search"></span>
                            </a>
                            <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                                <span class="svg-icon icon-cancel"></span>
                            </a>
                            <span class="search-button search-loading" id="search-loading-mobile">
                                <span class="svg-icon icon-loading"></span>
                            </span>
                        </div>
                        <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                            取消
                        </a>
                    </div><nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul><li>
                            <a class="menu-item" href="/posts/" title="">目录</a>
                        </li><li>
                            <a class="menu-item" href="/tags/" title="">标签</a>
                        </li><li>
                            <a class="menu-item" href="/categories/" title="">归档</a>
                        </li><li>
                            <a class="menu-item" href="/comments/" title="">留言</a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" title="" rel="noopener noreffer" target="_blank">主页</a>
                        </li></ul>
                </nav>
                <a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <span class="svg-icon icon-moon"></span>
                </a></div>
        </div>
    </div><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div></header><main class="main">
<div class="container content-article page-toc theme-classic"><div class="toc" id="toc-auto">
            <div class="toc-title">目录</div>
            <div class="toc-content" id="toc-content-auto"></div>
        </div>
    

    
    
    <article>
    

        <header class="header-post">

            

            
            <div class="post-title">

                    <div class="post-all-meta">
                        <nav class="breadcrumbs">
    <ol>
        <li><a href="/">主页 </a></li><li><a href="/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">TF2.1学习笔记 </a></li><li>TensorFlow2.1入门学习笔记(6)——激活函数</li>
    </ol>
</nav>
                        <h1 class="single-title flipInX">TensorFlow2.1入门学习笔记(6)——激活函数</h1><div class="post-meta summary-post-meta"><span class="post-category meta-item">
                                <a href="/categories/tf2.1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"><span class="svg-icon icon-folder"></span>TF2.1学习笔记</a>
                            </span><span class="post-meta-date meta-item">
                                <span class="svg-icon icon-clock"></span><time class="timeago" datetime="2020-05-20">2020-05-20</time>
                            </span><span class="post-meta-words meta-item">
                                <span class="svg-icon icon-pencil"></span>约 1667 字
                            </span>
                            <span class="post-meta-reading meta-item">
                                <span class="svg-icon icon-stopwatch"></span>预计阅读 4 分钟
                            </span>
                        </div>

                    </div>

                </div>

                </header>

        <div class="article-post toc-start">

            <div class="content-block content-block-first content-block-position">

                <div class="post single"><div class="details toc" id="toc-static"  data-kept="">
                        <div class="details-summary toc-title">
                            <span>目录</span>
                        </div>
                        <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#常见函数">常见函数</a>
          <ul>
            <li>
              <ul>
                <li><a href="#tfwhere条件语句真返回a假返回b">tf.where(条件语句，真返回A，假返回B)</a></li>
                <li><a href="#nprandomrandomstaterand维度">np.random.RandomState.rand(维度)</a></li>
                <li><a href="#npvstack数组1数组2">np.vstack(数组1，数组2)</a></li>
                <li><a href="#npmgrid">np.mgrid[]</a></li>
                <li><a href="#xravel">x.ravel()</a></li>
                <li><a href="#npc_">np.c_[]</a>
                  <ul>
                    <li><a href="#例">例：</a></li>
                  </ul>
                </li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#神经网络nn复杂度">神经网络（NN）复杂度</a></li>
        <li><a href="#学习率">学习率</a></li>
        <li><a href="#激活函数">激活函数</a>
          <ul>
            <li>
              <ul>
                <li><a href="#好的激活函数的特点">好的激活函数的特点：</a></li>
                <li><a href="#激活函数输出值的范围">激活函数输出值的范围：</a></li>
                <li><a href="#常用的激活函数">常用的激活函数</a>
                  <ul>
                    <li><a href="#sigmoid函数tfnnsigmoidx">Sigmoid函数：tf.nn.sigmoid(x)</a></li>
                    <li><a href="#tanh函数tfmathtanhx">Tanh函数：tf.math.tanh(x)</a></li>
                    <li><a href="#relu函数tfnnrelux">Relu函数：tf.nn.relu(x)</a></li>
                    <li><a href="#leaky-relu函数tfnnleaky_relux">Leaky Relu函数：tf.nn.leaky_relu(x)</a></li>
                    <li><a href="#summarize">SUMMARIZE</a></li>
                  </ul>
                </li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav></div>
                    </div><h3 id="常见函数" class="headerLink"><a href="#%e5%b8%b8%e8%a7%81%e5%87%bd%e6%95%b0" class="header-mark"></a>常见函数</h3><h5 id="tfwhere条件语句真返回a假返回b" class="headerLink"><a href="#tfwhere%e6%9d%a1%e4%bb%b6%e8%af%ad%e5%8f%a5%e7%9c%9f%e8%bf%94%e5%9b%9ea%e5%81%87%e8%bf%94%e5%9b%9eb" class="header-mark"></a>tf.where(条件语句，真返回A，假返回B)</h5><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span>
<span class="c1"># 若a&gt;b，返回a对应位置的元素，否则返回b对应位置的元素</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">greater</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">),</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>  
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;c：&#34;</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>		<span class="c1"># c： tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)</span>
</code></pre></td></tr></table>
</div>
</div><h5 id="nprandomrandomstaterand维度" class="headerLink"><a href="#nprandomrandomstaterand%e7%bb%b4%e5%ba%a6" class="header-mark"></a>np.random.RandomState.rand(维度)</h5><p>返回一个[0, 1)之间的随机数</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="n">rdm</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">RandomState</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">rdm</span><span class="o">.</span><span class="n">rand</span><span class="p">()</span>		<span class="c1"># 返回一个随机标量</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">rdm</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>	<span class="c1"># 返回一个维度为2行3列的随机数矩阵</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;a:&#34;</span><span class="p">,</span><span class="n">a</span><span class="p">)</span>		<span class="c1"># a: 0.417022004702574</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;b:&#34;</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>		<span class="c1"># b: [[7.20324493e-01 1.14374817e-04 3.02332573e-01][1.46755891e-01 9.23385948e-02 1.86260211e-01]]</span>
</code></pre></td></tr></table>
</div>
</div><h5 id="npvstack数组1数组2" class="headerLink"><a href="#npvstack%e6%95%b0%e7%bb%841%e6%95%b0%e7%bb%842" class="header-mark"></a>np.vstack(数组1，数组2)</h5><p>将两个数组按垂直方向叠加</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">vstack</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;c:&#34;</span><span class="p">,</span><span class="n">c</span><span class="p">)</span>		<span class="c1"># c:[[1 2 3][4 5 6]]</span>
</code></pre></td></tr></table>
</div>
</div><h5 id="npmgrid" class="headerLink"><a href="#npmgrid" class="header-mark"></a>np.mgrid[]</h5><p>np.mgrid[起始值 : 结束值 : 步长，起始值 : 结束值 : 步长, ……]
包含起始值，不包含结束值</p>
<h5 id="xravel" class="headerLink"><a href="#xravel" class="header-mark"></a>x.ravel()</h5><p>x.ravel()
将x变为一维数组，将变量拉直</p>
<h5 id="npc_" class="headerLink"><a href="#npc_" class="header-mark"></a>np.c_[]</h5><p>np.c_[数组1，数组2，……]
使返回的间隔数值点配对</p>
<h6 id="例" class="headerLink"><a href="#%e4%be%8b" class="header-mark"></a>例：</h6><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mgrid</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">:</span><span class="mi">4</span><span class="p">:</span><span class="mf">0.5</span><span class="p">]</span>
<span class="n">grid</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">x</span><span class="o">.</span><span class="n">ravel</span><span class="p">(),</span><span class="n">y</span><span class="o">.</span><span class="n">ravel</span><span class="p">()]</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;x:&#34;</span><span class="p">,</span><span class="n">x</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;y:&#34;</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&#34;grid:</span><span class="se">\n</span><span class="s2">&#34;</span><span class="p">,</span><span class="n">grid</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519145207309.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519145207309.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h3 id="神经网络nn复杂度" class="headerLink"><a href="#%e7%a5%9e%e7%bb%8f%e7%bd%91%e7%bb%9cnn%e5%a4%8d%e6%9d%82%e5%ba%a6" class="header-mark"></a>神经网络（NN）复杂度</h3><ul>
<li>NN复杂度：用NN层数和NN参数的个数表示</li>
<li>空间复杂度：层数 = 隐藏层的层数 + 1个输出层</li>
<li>总参数：总w数 + 总b数</li>
<li>时间复杂度：乘加运算次数</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519145726936.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519145726936.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h3 id="学习率" class="headerLink"><a href="#%e5%ad%a6%e4%b9%a0%e7%8e%87" class="header-mark"></a>学习率</h3><p>选择合适的学习率来更新参数</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519150412319.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519150412319.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<ul>
<li>指数衰减学习率
$指数衰减学习率 = 初始学习率*学习率衰减率^\frac{当前层数}{多少轮衰减一次}$</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="kn">as</span> <span class="nn">tf</span>

<span class="n">w</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">float32</span><span class="p">))</span>

<span class="n">epoch</span> <span class="o">=</span> <span class="mi">40</span>
<span class="n">LR_BASE</span> <span class="o">=</span> <span class="mf">0.2</span>  		<span class="c1"># 最初学习率</span>
<span class="n">LR_DECAY</span> <span class="o">=</span> <span class="mf">0.99</span>  	<span class="c1"># 学习率衰减率</span>
<span class="n">LR_STEP</span> <span class="o">=</span> <span class="mi">1</span>			<span class="c1"># 喂入多少轮BATCH_SIZE后，更新一次学习率</span>

<span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">epoch</span><span class="p">):</span>  <span class="c1"># for epoch 定义顶层循环，表示对数据集循环epoch次，此例数据集数据仅有1个w,初始化时候constant赋值为5，循环100次迭代。</span>
    <span class="n">lr</span> <span class="o">=</span> <span class="n">LR_BASE</span> <span class="o">*</span> <span class="n">LR_DECAY</span> <span class="o">**</span> <span class="p">(</span><span class="n">epoch</span> <span class="o">/</span> <span class="n">LR_STEP</span><span class="p">)</span>
    <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">GradientTape</span><span class="p">()</span> <span class="k">as</span> <span class="n">tape</span><span class="p">:</span>  	<span class="c1"># with结构到grads框起了梯度的计算过程。</span>
        <span class="n">loss</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">square</span><span class="p">(</span><span class="n">w</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">grads</span> <span class="o">=</span> <span class="n">tape</span><span class="o">.</span><span class="n">gradient</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="n">w</span><span class="p">)</span>  	<span class="c1"># .gradient函数告知谁对谁求导</span>

    <span class="n">w</span><span class="o">.</span><span class="n">assign_sub</span><span class="p">(</span><span class="n">lr</span> <span class="o">*</span> <span class="n">grads</span><span class="p">)</span> 			<span class="c1"># .assign_sub 对变量做自减 即：w -= lr*grads 即 w = w - lr*grads</span>
    <span class="k">print</span><span class="p">(</span><span class="s2">&#34;After </span><span class="si">%s</span><span class="s2"> epoch,w is </span><span class="si">%f</span><span class="s2">,loss is </span><span class="si">%f</span><span class="s2">,lr is </span><span class="si">%f</span><span class="s2">&#34;</span> <span class="o">%</span> <span class="p">(</span><span class="n">epoch</span><span class="p">,</span> <span class="n">w</span><span class="o">.</span><span class="n">numpy</span><span class="p">(),</span> <span class="n">loss</span><span class="p">,</span> <span class="n">lr</span><span class="p">))</span>
</code></pre></td></tr></table>
</div>
</div><p>运行结果：</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519152159165.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519152159165.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h3 id="激活函数" class="headerLink"><a href="#%e6%bf%80%e6%b4%bb%e5%87%bd%e6%95%b0" class="header-mark"></a>激活函数</h3><p>简化模型始终是线性函数，影响模型的表达力
MP模型多了一个非线性函数（激活函数），使得多层神经网络不再是线性，提高层数来提高模型表达力</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519152818724.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519152818724.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h5 id="好的激活函数的特点" class="headerLink"><a href="#%e5%a5%bd%e7%9a%84%e6%bf%80%e6%b4%bb%e5%87%bd%e6%95%b0%e7%9a%84%e7%89%b9%e7%82%b9" class="header-mark"></a>好的激活函数的特点：</h5><ul>
<li>非线性：激活函数非线性时，多层神经网络可以逼近所有函数</li>
<li>可微性：优化器大多用梯度下降更新参数</li>
<li>单调性 ：当激活函数是单调的，能保证单层神经网络的损失函数是凸函数（更容易收敛）</li>
<li>近似恒等性：$f(x)\approx x$当参数初始化为随机小值时，神经网路更稳定</li>
</ul>
<h5 id="激活函数输出值的范围" class="headerLink"><a href="#%e6%bf%80%e6%b4%bb%e5%87%bd%e6%95%b0%e8%be%93%e5%87%ba%e5%80%bc%e7%9a%84%e8%8c%83%e5%9b%b4" class="header-mark"></a>激活函数输出值的范围：</h5><ul>
<li>激活函数为有限值时，基于梯度下降的优化方法更稳定</li>
<li>激活函数输出为无限值时，可调小学习率</li>
</ul>
<h5 id="常用的激活函数" class="headerLink"><a href="#%e5%b8%b8%e7%94%a8%e7%9a%84%e6%bf%80%e6%b4%bb%e5%87%bd%e6%95%b0" class="header-mark"></a>常用的激活函数</h5><h6 id="sigmoid函数tfnnsigmoidx" class="headerLink"><a href="#sigmoid%e5%87%bd%e6%95%b0tfnnsigmoidx" class="header-mark"></a>Sigmoid函数：tf.nn.sigmoid(x)</h6><p><strong><font color=red>$f(x)=\frac{1}{1+e^{-x}}$</strong></font></p>
<ul>
<li>特点:</li>
</ul>
<ol>
<li>易造成梯度消失</li>
<li>输出非0均值，收敛慢</li>
<li>幂运算复杂，训练时间长</li>
</ol>
<ul>
<li>函数图像</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519173052938.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519173052938.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h6 id="tanh函数tfmathtanhx" class="headerLink"><a href="#tanh%e5%87%bd%e6%95%b0tfmathtanhx" class="header-mark"></a>Tanh函数：tf.math.tanh(x)</h6><p><strong><font color=red>$f(x)=\frac{1-e^{-2x}}{1+e^{-2x}}$</strong></font></p>
<ul>
<li>特点</li>
</ul>
<ol>
<li>输出是0均值</li>
<li>易造成梯度消失</li>
<li>幂运算复杂，训练时间长</li>
</ol>
<ul>
<li>函数图像</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519173423359.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519173423359.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h6 id="relu函数tfnnrelux" class="headerLink"><a href="#relu%e5%87%bd%e6%95%b0tfnnrelux" class="header-mark"></a>Relu函数：tf.nn.relu(x)</h6><p><strong><font color=red>$f(x)=max(x,0)$</strong></font></p>
<ul>
<li>优点</li>
</ul>
<ol>
<li>解决了梯度消失问题（在正区间内）</li>
<li>只需判断输入是否大于0，计算速度快</li>
<li>收敛速度远快于sigmoid和tanh</li>
</ol>
<ul>
<li>缺点</li>
</ul>
<ol start="4">
<li>输出非0均值，收敛慢</li>
<li>Dead Relu问题：某些神经元可能永远不会被激活，导致相应的参数不能被更新</li>
</ol>
<ul>
<li>函数图像</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519174108758.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519174108758.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h6 id="leaky-relu函数tfnnleaky_relux" class="headerLink"><a href="#leaky-relu%e5%87%bd%e6%95%b0tfnnleaky_relux" class="header-mark"></a>Leaky Relu函数：tf.nn.leaky_relu(x)</h6><p><strong><font color=red>$f(x)=max(\alpha x,x)$</strong></font></p>
<ul>
<li>特点：理论上来说，Leaky Relu有Relu的所有优点，也不会出现Dead Relu问题，但是在实际使用过程中，并没有完全证明比Relu好用</li>
<li>函数图像</li>
</ul>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200519174542405.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200519174542405.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<h6 id="summarize" class="headerLink"><a href="#summarize" class="header-mark"></a>SUMMARIZE</h6><ul>
<li>首选relu函数</li>
<li>学习率设置较小值</li>
<li>输入特征标准化，即让输入特征满足以0为均值，1为标准差的正态分布</li>
<li>初始化中心化，即让随机数生成的参数满足以0为均值，$\sqrt{\frac{2}{当前输入特征个数}}$为正态分布</li>
</ul>
<p>主要学习的资料，西安科技大学：<a href="https://www.icourse163.org/learn/XUST-1206363802#/learn/announce" target="_blank" rel="noopener noreffer">神经网络与深度学习——TensorFlow2.0实战</a>，北京大学：<a href="https://www.icourse163.org/learn/PKU-1002536002#/learn/announce" target="_blank" rel="noopener noreffer">人工智能实践Tensorflow笔记</a></p>
</div><footer>
                        <div class="post">


<div class="post-share"><div class="share-link">
        <a class="share-icon share-twitter" href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://blog.aimoon.top/activation/" data-title="TensorFlow2.1入门学习笔记(6)——激活函数" data-via="wangyuexin8" data-hashtags="activation,function"><span class="svg-social-icon icon-twitter"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-facebook" href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://blog.aimoon.top/activation/" data-hashtag="activation"><span class="svg-social-icon icon-facebook"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-whatsapp" href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://blog.aimoon.top/activation/" data-title="TensorFlow2.1入门学习笔记(6)——激活函数" data-web><span class="svg-social-icon icon-whatsapp"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-blogger" href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://blog.aimoon.top/activation/" data-title="TensorFlow2.1入门学习笔记(6)——激活函数" data-description=""><span class="svg-social-icon icon-blogger"></span></a>
    </div></div>

<div class="footer-post-author">
    <div class="author-avatar"><a href="https://aimoon.top" target="_blank"><img alt="Undergraduate Student of Artificial Intelligence 😜" src="https://blog.aimoon.top/images/avatars.png"></a></div>
    <div class="author-info">
        <div class="name"><a href="https://aimoon.top" target="_blank">Wang Yuexin</a></div>
        <div class="number-posts">Undergraduate Student of Artificial Intelligence 😜</span></div>
    </div>
</div><div class="post-tags"><a href="/tags/activation/" class="tag">activation</a><a href="/tags/function/" class="tag">function</a></div></div>
                </footer></div>
        <div id="toc-final"></div>
        </div>

    
    </article>
    <section class="page single comments content-block-position">
        <h1 class="display-hidden">Комментарии</h1><div id="comments"><div id="disqus_thread" class="comment" style="padding-top: 1.5rem"></div>
            <noscript>
                Please enable JavaScript to view the comments powered by <a href="https://disqus.com/?ref_noscript">Disqus</a>.
            </noscript></div></section></div>

</main><footer class="footer">
        <div class="footer-container"><div class="footer-line"><div><span id="timeDate">正在烧脑计算建站时间...</span><span id="times"></span><script>var now = new Date();function createtime(){var grt= new Date("05/20/2020 00:00:00");now.setTime(now.getTime()+250);days = (now - grt ) / 1000 / 60 / 60 / 24;dnum = Math.floor(days);hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);hnum = Math.floor(hours);if(String(hnum).length ==1 ){hnum = "0" + hnum; }minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);mnum = Math.floor(minutes);if(String(mnum).length ==1 ){mnum = "0" + mnum;}seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);snum = Math.round(seconds);if(String(snum).length ==1 ){snum = "0" + snum;}document.getElementById("timeDate").innerHTML = "&nbsp"+dnum+"&nbsp天";document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";}setInterval("createtime()",250);</script></div></div><div class="footer-line"><i class="svg-icon icon-copyright"></i><span>2020 - 2021</span><span class="author">&nbsp;<a href="https://aimoon.top" target="_blank">Yasin</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span><span class="icp-splitter">&nbsp;|&nbsp;</span><br class="icp-br"/>
                    <span class="icp"><a href="https://blog.pangao.vip/icp/xmoon.info">🧑ICP证000000号</a></span></div>
        </div>
    </footer></div>

        <aside id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="svg-icon icon-arrow-up"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="svg-icon icon-comments-fixed"></i>
            </a>
        </aside><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script src="https://yasin5.disqus.com/embed.js" defer></script><script src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script src="https://cdn.jsdelivr.net/npm/lunr@2.3.8/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="https://cdn.jsdelivr.net/npm/twemoji@13.0.0/dist/twemoji.min.js"></script><script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/mhchem.min.js"></script><script src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":30,"type":"lunr"},"twemoji":true};</script><script src="/js/theme.min.js"></script><script>
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

	        ga('create', 'UA-167439955-2', 'auto');
	        ga('set', 'anonymizeIp', true);
	        ga('send', 'pageview');
	    </script></body>
</html>
